<?php

namespace app\call\controller;

use app\admin\model\Config;
use app\api\model\Bill;
use app\api\model\GameLog;
use app\api\model\Member;
use EasyWeChat\Factory;
use think\cache\driver\Redis;
use think\Db;
use think\Exception;
use think\facade\Log;

class Game
{
    public function getLoginQrcode()
    {
        $params = request()->param();
        Log::info('getLoginQrcode-请求信息:' . json_encode($params, JSON_UNESCAPED_UNICODE));
        try {
            $this->checkSign($params);
            $uniqid = uniqid();
            //生成二维码
            $app = Factory::miniProgram(config('wechat.xcx'));

            $response = $app->app_code->get('pages/login/index?uniqid=' . $uniqid);
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $filename = $response->saveAs('uploads/qrcode/', $uniqid);
            } else {
                throw new Exception('生成二维码失败');
            }
            $qrcode = env('domain.image_url') . '/uploads/qrcode/' . $filename;
            Log::write(json_encode(['uniqid' => $uniqid, 'qrcode' => $qrcode]));

            return json(['code' => 0, 'msg' => '获取成功', 'data' => ['uniqid' => $uniqid, 'qrcode' => $qrcode]]);
        } catch (\Exception $e) {
            Log::error('getLoginQrcode-' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage(), 'data' => []]);
        }
    }


    protected function checkSign($params = array()){
        $sign = $params['sign'] ?? '';
        $timestamp = $params['timestamp'] ?? '';
        if (!$sign || !$timestamp) {
            throw new Exception('缺少参数');
        }
        //验证参数
        if ($sign != $this->createSdkSign($params)) {
            throw new Exception('签名错误');
        }
        if ($timestamp + 300 < time()) {
            throw new Exception('签名已过期');
        }
    }


    public function userIsLogin()
    {
        $params = request()->param();
        Log::info('userIsLogin-请求信息:' . json_encode($params, JSON_UNESCAPED_UNICODE));

        try {
           $this->checkSign($params);
            $uniqid = $params['uniqid'] ?? '';
            if (!$uniqid) {
                throw new Exception('没有登录');
            }
            $redis = new Redis();
            $user = $redis->get($uniqid);
            if (!$user) {
                throw new Exception('没有登录');
            }
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $user]);
        } catch (\Exception $e) {
            Log::error('getLoginQrcode-' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage(), 'data' => []]);
        }
    }


    public function reportIntegral()
    {
        $params = request()->param();
        $user_id = $params['user_id'] ?? '';
        $game_id = $params['game_id'] ?? '';
        $integral = $params['integral'] ?? 0;
        Log::info('reportIntegral-请求信息:' . json_encode($params, JSON_UNESCAPED_UNICODE));
        try {
           $this->checkSign($params);
           if(!$user_id || !$game_id){
               throw new Exception('缺少参数');
           }
            $member = (new Member())->where(['id' => $user_id])->find();
            if (!$member) {
                throw new Exception('用户不存在');
            }
            $game = (new \app\admin\model\Game())->where(['id' => $game_id])->find();
            if (!$game) {
                throw new Exception('游戏不存在');
            }

            //查询获取今日的积分
            $start_time =strtotime(date("Y-m-d"));
            $end_time =$start_time + 86400;
            $map[] = ['member_id','=',$user_id];
            $map[] = ['type','=',1];
            $map[] = ['create_time','>',$start_time];
            $map[] = ['create_time','<',$end_time];
            $member_integrate = (new Bill())->where($map)->sum('income');
            $integrate_limit = (new Config())->where(['name' => 'points_limit'])->value('value');
            if($member_integrate >= $integrate_limit){
                return json(['code' => 0, 'msg' => '上报成功', 'data' => []]);
            }
            \think\facade\Db::startTrans();
            //上报积分
            if (!(new Bill())->addBill($member, $integral, $game['name'], 1)) {
                throw new Exception('上报失败');
            }
            $data['total_integral'] = $member['total_integral'] + $integral;
            $data['residue_integral'] = $member['residue_integral'] + $integral;
            if (!(new Member())->where(['id' => $member['id']])->update($data)) {
                throw new Exception('上报失败');
            }

            $gameLog['member_id'] = $member['id'];
            $gameLog['game_id'] = $game_id;
            $gameLog['create_time'] = time();
            $gameLog['update_time'] = time();
            $gameLog['game_type'] = $game['type'];
            (new GameLog())->insert($gameLog);


            \think\facade\Db::commit();
            return json(['code' => 0, 'msg' => '上报成功', 'data' => []]);
        } catch (\Exception $e) {
            \think\facade\Db::rollback();
            Log::error('getLoginQrcode-' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage(), 'data' => []]);
        }
    }


    public function getUserGameLog()
    {
        $params = request()->param();

        $user_id = $params['user_id'] ?? 0;
        $game_id = $params['game_id'] ?? 0;
        Log::info('getUserGameLog-请求信息:' . json_encode($params, JSON_UNESCAPED_UNICODE));
        try {
            $this->checkSign($params);
            $gameLog = (new GameLog())
                ->where(['member_id' => $user_id, 'status' => 1, 'game_type' => 1])
                ->order('game_id desc,status desc')->find();
            $userGame = $gameLog['game_id'] ?? 0;
            if ($userGame + 1 != $game_id) {
                throw new Exception('不能玩');
            }
            return json(['code' => 0, 'msg' => '可以玩', 'data' => []]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => $e->getMessage(), 'data' => []]);
        }
    }


    public function getUserIntegral()
    {
        try {
            $params = request()->param();
            $count = $params['count'] ?? null; // 将默认值设置为 null
            Log::info('getUserIntegral-请求信息:' . json_encode($params, JSON_UNESCAPED_UNICODE));
            $this->checkSign($params);
            $query = (new Member())->where(['status' => 1])
                ->order('residue_integral desc')
                ->field('id,nickname,residue_integral');
            if ($count && is_numeric($count) && $count > 0) {
                $query->limit($count);
            }
            $list = $query->select();
            return json(['code' => 0, 'msg' => 'success', 'data' => $list]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => $e->getMessage(), 'data' => []]);
        }
    }



    public function createSdkSign($params)
    {
        unset($params['sign']);
        $secret = 'game@HbnbwU';
        ksort($params);
        $str = http_build_query($params) . $secret;
//        print_r(strtolower(md5($str)));
        return strtolower(md5($str));
    }
}